package com.yc.mvc.web;

import com.yc.mvc.bean.User;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.PrintWriter;

@Controller//Controller表示类的每个方法返回的是视图
@RequestMapping("param")
public class ParamController {
    @GetMapping("hello")
    @ResponseBody//表示该方法返回json参数
    public String hello(String name) {
        return "hello" + name;
    }


    @GetMapping("add")
    @ResponseBody
    public int add(@RequestParam(name = "x", defaultValue = "5") int a,
                   @RequestParam(name = "y", defaultValue = "3") int b,
                   boolean c) {

        return c ? a + b : a - b;
    }

    //自动装配
    @GetMapping("reg")
    @ResponseBody
    public User reg(User user) {
        return user;
    }

    @GetMapping(path = "servlet", produces = MediaType.TEXT_HTML_VALUE)
    public void servlet(HttpServletRequest request,
                        HttpServletResponse response,
                        HttpSession session,
                        InputStream in,
                        PrintWriter out) {
        response.setContentType("text/html");
        out.append("ul")
                .append("<li>").append(request.toString())
                .append("<li>").append(request.toString())
                .append("<li>").append(request.toString())
                .append("<li>").append(request.toString())
                .append("<li>").append(request.toString())
                .append("</ul>");
    }

    //地址参数不是请求参数
    //127.0.0.1/xxx/ppp/aaa? ppp地址参数
    @GetMapping("user/{id}")//user/123
    @ResponseBody
    public String pathVariable(@PathVariable int id) {
        return id + "";
    }

    //获取头域参数
    @GetMapping(path = "header1", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String header1(
            @RequestHeader String Host,//按名字匹配
            @RequestHeader(value = "Accept", required = false) String accept,
            @RequestHeader(value = "Cookie", required = false) String cookie) {
        return Host + "<br>" +accept+ "<br>" +cookie+ "<br>" ;

    }

    @GetMapping("cookie")
    @ResponseBody
    public String cookie(@CookieValue(value = "name", required = false) String name) {
        return "cookie:" +name;
    }
}
